<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>签名案例</title>
	</head>

	<body>
		<canvas id="canvas" style="border: 1px solid red; "></canvas>
		<button id="button">清除画面</button>
		<script>
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var cxt = canvas.getContext("2d");
				canvas.width = 400;
				canvas.height = 300;
				var canvasx = canvas.getBoundingClientRect().left;
				var canvasy = canvas.getBoundingClientRect().top;
				console.log(canvasx);
				console.log(canvasy);
				canvas.addEventListener("mousedown", downfun);
				canvas.addEventListener("mousemove", movefun);
				canvas.addEventListener("mouseup", upfun);
				//canvas.onmousedown=function(){}
				//canvas.onmousemove=function(){}
				//canvas.onmouseup=function(){}
				var startx; //起始坐标 X
				var starty; //起始坐标 Y
				var endx; //结束坐标 X
				var endy; //结束坐标 Y
				cxt.lineWidth = 3; //设置线宽 3
				var offon = false; //锁定开关
				//鼠标按下
				function downfun(e) {
					offon = true;
					startx = e.clientX - canvasx;
					starty = e.clientY - canvasy;

				}
				//鼠标移动
				function movefun(e) {
					if(offon == true) {
						cxt.beginPath()
						endx = e.clientX - canvasx;
						endy = e.clientY - canvasy;
						cxt.moveTo(startx, starty);
						cxt.lineTo(endx, endy);
						cxt.stroke();

						startx = endx;
						starty = endy;
						console.log("1111");
					}
				}
				//鼠标离开
				function upfun() {
					offon = false;
					cxt.closePath();
				}
				//清除画面
				document.getElementById("button").onclick = function() {
					cxt.clearRect(0, 0, canvas.width, canvas.height);
				}
			}
		</script>
	</body>

</html>